/* eslint-disable react/jsx-indent */
import React, { PureComponent } from 'react';
import router from 'umi/router';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Row, Col, Modal, Select, Steps, Button, Input, Radio, Divider } from 'antd';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import AddEmpForm from '../../SocialService/SocialCard/AddEmpForm';
import AddEmpInfor from '../../SocialService/SocialCard/AddEmpInfor';
import AddMatInfor from '../../SocialService/SocialCard/AddMatInfor';

const { confirm } = Modal;
const FormItem = Form.Item;
const { Step } = Steps;
const { Option } = Select;
const steps = [
  {
    title: '查询员工',
    content: 'First-content',
  },
  {
    title: '发起办理',
    content: 'Second-content',
  },
];
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 9,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: { span: 7 },
  },
};
const formItemLayouts = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 10,
    },
    xl: { span: 10 },
    xxl: { span: 10 },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const RadioGroup = Radio.Group;
@connect(
  ({
    publicdata: { serviceTypeList },
    handle: {
      sendData,
      empNameSelect,
      empNameList,
      elementArr,
      matFileDictItem,
      messageData,
      coltFlag,
    },

    loading,
  }) => ({
    // 对应的文件名：{方法名}
    elementArr,
    matFileDictItem,
    sendData,
    empNameList,
    empNameSelect,
    serviceTypeList,
    messageData,
    coltFlag,
    loading: loading.effects['handle/fetchEmpNameList']&&loading.effects['handle/addList'],
  })
)
class AccuAdd extends PureComponent {
  state = {
    current: 0,
    btnDis: true,
    refundFlag: 2,
    visNext: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'handle/clearEmpName',
      payload: {},
    });
    dispatch({
      type: 'publicdata/serviceType',
      payload: { serType: 1 },
    });
  }

  prev = () => {
    const { current } = this.state;
    const current1 = current - 1;
    this.setState({ current: current1, btnDis: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'handle/clearEmpName',
      payload: {},
    });
    this.setState({
      refundFlag: 2,
    });
  };

  baseData = () => {};

  serviceType = value => {
    this.setState({
      serTypeId: value.key,
      serTypeName: value.label,
    });
  };

  saveUpdate = () => {
    const { location, form } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/add')[0];
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (err) return;
      const matlist = [];
      const insSerHdl = {};
      const tempValues = values;
      Object.keys(tempValues).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(tempValues[key].inpType) === '9') {
            let file = '';
            if (tempValues[key].fileList && tempValues[key].fileList.length) {
              tempValues[key].fileList.forEach(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                }
              });
              tempValues[key].inpVal = file ? file.slice(0, file.length - 1) : '';
            }
          }
          tempValues[key].pkgPageDetailId = tempValues[key].pageDetailId;
          matlist.push(tempValues[key]);
        } else if (key === 'matFlag') {
          insSerHdl.matFlag = tempValues[key];
        } else if (key === 'copyFiles') {
          insSerHdl.copyFiles = tempValues[key];
        } else if (key === 'masterFiles') {
          insSerHdl.masterFiles = tempValues[key];
        }
      });
      const { empNameSelect, dispatch } = this.props;
      const { serTypeId, refundFlag } = this.state;
      insSerHdl.sendId = empNameSelect[0].sendId;
      insSerHdl.source = empNameSelect[0].dataSource;
      insSerHdl.areaId = empNameSelect[0].areaId;
      insSerHdl.serTypeId = serTypeId;
      insSerHdl.refundFlag = refundFlag;
      if (String(refundFlag) === '1') {
        insSerHdl.payeeBankcardNo = tempValues.payeeBankcardNo;
        insSerHdl.payeeBankOfDepo = tempValues.payeeBankOfDepo;
        insSerHdl.payeeName = tempValues.payeeName;
      }

      insSerHdl.submitFlag = '1';
      const param = {
        matlist,
        insSerHdl,
      };

      dispatch({
        type: 'handle/addCheckList',
        payload: param,
        callback: response => {
          if (response) {
            if (response.data.code === '201') {
              message.error('该员工正在办理此服务类型，不能新增!');
            } else if (response.data.code === '202') {
              confirm({
                content: '当前人员已办理过此项业务，确定再次办理?',
                okText: '确定',
                icon: <QuestionCircleOutlined />,
                cancelText: '取消',
                onOk() {
                  dispatch({
                    type: 'handle/addList',
                    payload: param,
                    callback: res => {
                      if (res.success) {
                        router.push(`${tempUrl}/index`);
                      }
                    },
                  });
                },
                onCancel() {},
              });
            } else if (response.data.code === '200') {
              router.push(`${tempUrl}/index`);
            }
          }
        },
      });
    });
  };

  save = () => {
    const { location, form } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/add')[0];
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (err) return;
      const matlist = [];
      const insSerHdl = {};
      const tempValues = values;
      Object.keys(tempValues).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(tempValues[key].inpType) === '9') {
            let file = '';
            if (tempValues[key].fileList && tempValues[key].fileList.length) {
              tempValues[key].fileList.forEach(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                }
              });
              tempValues[key].inpVal = file ? file.slice(0, file.length - 1) : '';
            }
          }
          tempValues[key].pkgPageDetailId = tempValues[key].pageDetailId;
          matlist.push(tempValues[key]);
        } else if (key === 'matFlag') {
          insSerHdl.matFlag = tempValues[key];
        } else if (key === 'copyFiles') {
          insSerHdl.copyFiles = tempValues[key];
        } else if (key === 'masterFiles') {
          insSerHdl.masterFiles = tempValues[key];
        }
      });
      const { empNameSelect, dispatch } = this.props;
      const { serTypeId, refundFlag } = this.state;
      insSerHdl.sendId = empNameSelect[0].sendId;
      insSerHdl.source = empNameSelect[0].dataSource;
      insSerHdl.areaId = empNameSelect[0].areaId;
      insSerHdl.serTypeId = serTypeId;
      insSerHdl.refundFlag = refundFlag;
      if (String(refundFlag) === '1') {
        insSerHdl.payeeBankcardNo = tempValues.payeeBankcardNo;
        insSerHdl.payeeBankOfDepo = tempValues.payeeBankOfDepo;
        insSerHdl.payeeName = tempValues.payeeName;
      }

      insSerHdl.submitFlag = '2';
      const param = {
        matlist,
        insSerHdl,
      };
      dispatch({
        type: 'handle/addCheckList',
        payload: param,
        callback: response => {
          if (response) {
            if (response.data.code === '201') {
              message.error('该员工正在办理此服务类型，不能新增！');
            } else if (response.data.code === '202') {
              confirm({
                content: '当前人员已办理过此项业务，确定再次办理?',
                okText: '确定',
                icon: <QuestionCircleOutlined />,
                cancelText: '取消',
                onOk() {
                  dispatch({
                    type: 'handle/addList',
                    payload: param,
                    callback: res => {
                      if (res.success) {
                        router.push(`${tempUrl}/index`);
                      }
                    },
                  });
                },
                onCancel() {},
              });
            } else if (response.data.code === '200') {
              router.push(`${tempUrl}/index`);
            }
          }
        },
      });
    });
  };

  refunds = e => {
    this.setState({
      refundFlag: e.target.value,
    });
  };

  onSelectData = element => {
    const { elementArr, dispatch } = this.props;
    dispatch({
      type: 'handle/matInfor',
      payload: { elementArr, element },
    });
  };

  empData = (data, flag) => {
    const { dispatch } = this.props;
    this.setState({
      btnDis: flag,
    });
    dispatch({
      type: 'handle/fetchEmpName',
      payload: data,
    });
  };

  empSearch = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handle/fetchEmpNameList',
      payload: values,
    });
  };

  idVailFunc = values => {
    const { dispatch } = this.props;
    if (values) {
      dispatch({
        type: 'handle/fetchEmpNoList',
        payload: values,
        callback: res => {
          this.setState({
            btnDis: res,
          });
        },
      });
    }
  };

  next = () => {
    const { dispatch, empNameSelect, form } = this.props;
    const { serTypeId, current } = this.state;
    form.validateFieldsAndScroll({ force: true }, err => {
      if (err) return;
      dispatch({
        type: 'handle/checkSocial',
        payload: { sendId: empNameSelect[0].sendId, serTypeId },
        callback: isDisabled => {
          if (isDisabled) {
            this.setState({ visNext: true });
          } else {
            const current1 = current + 1;
            this.setState({ current: current1 });
            dispatch({
              type: 'handle/fetchMatList',
              payload: {
                serType: 1,
                serTypeId,
                areaId: empNameSelect[0].areaId,
              },
            });
            dispatch({
              type: 'handle/fetchSendInfor',
              payload: {  areaId: empNameSelect[0].areaId,sendId: empNameSelect[0].sendId, dataSource: empNameSelect[0].dataSource },
            });
          }
        },
      });
    });
  };

  okNext = () => {
    const { dispatch, empNameSelect } = this.props;
    const { current, serTypeId } = this.state;
    const current1 = current + 1;
    this.setState({ current: current1, visNext: false });
    dispatch({
      type: 'handle/fetchMatList',
      payload: { serType: 1, serTypeId, areaId: empNameSelect[0].areaId },
    });
    dispatch({
      type: 'handle/fetchSendInfor',
      payload: { sendId: empNameSelect[0].sendId, dataSource: empNameSelect[0].dataSource },
    });
  };

  cancelNext = () => {
    this.setState({ visNext: false });
  };

  close = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/add')[0];
    router.push(`${tempUrl}/index`);
  };

  checkElement = (rule, value, callback) => {
    let tip = '';
    switch (Number(value.inpType)) {
      case 1:
        tip = `请输入不超过30个字的${value.matName}`;
        break;
      case 9:
        tip = `请上传${value.matName}`;
        break;
      case 3:
        tip = `请输入不超过300个字的${value.matName}`;
        break;
      default:
        tip = `请选择${value.matName}`;
        break;
    }
    if (
      Number(value.inpType) !== 9
        ? rule.required && !value.inpVal
        : rule.required && !(value.fileList && value.fileList.length)
    ) {
      callback(tip);
    } else if (+value.inpType === 1 || +value.inpType === 3) {
      if (rule.max < (value.inpVal && value.inpVal.length)) {
        callback(tip);
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  render() {
    const { current, serTypeName, btnDis, refundFlag, visNext } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const {
      elementArr,
      matFileDictItem,
      sendData,
      serviceTypeList,
      empNameList,
      empNameSelect,
      messageData,
      coltFlag,
      loading,
    } = this.props;
    const { empSendInfoVo, empBaseInfoVo } = sendData;
    const max = val => {
      if (val === 1) return 30;
      if (val === 3) return 300;
      return null;
    };
    const renderElem = ele =>
      ele && ele.length ? (
        ele.map(element => (
          <Row key={element}>
            <Col span={8}>
              <FormItem {...formItemLayouts} label={<span> {element.matName}</span>}>
                {getFieldDecorator(`mat_${element.pageDetailId}`, {
                  rules: [
                    {
                      required: +element.reqFlag === 1,
                      validator: this.checkElement,
                      max: max(+element.inpType),
                    },
                  ],
                  initialValue: element,
                })(<AddMatInfor onChange={this.onSelectData} />)}
              </FormItem>
            </Col>
          </Row>
        ))
      ) : (
        <div />
      );

    return (
      <div>
        <PageHeaderWrapper>
          <Card style={{ marginBottom: 12, marginTop: 10 }}>
            <Steps current={current} style={{ width: 327, margin: '0 auto' }}>
              {steps.map(item => (
                <Step key={item.title} title={item.title} />
              ))}
            </Steps>
          </Card>
          <div className={styles.stepsAction}>
            {current === 0 && (
              <Card>
                <FormItem {...formItemLayout} label={<span>服务类型</span>}>
                  {getFieldDecorator('serTypeId', {
                    rules: [
                      {
                        required: true,
                        message: '请选择服务类型',
                      },
                    ],
                  })(
                    <HOCSelect
                      style={{ width: '100%' }}
                      showSearch
                      placeholder="请选择服务类型"
                      labelInValue
                      onChange={this.serviceType}
                    >
                      {serviceTypeList && serviceTypeList.length
                        ? serviceTypeList.map(options => (
                            <Option key={options.serTypeId}>{options.serTypeIdName}</Option>
                          ))
                        : null}
                    </HOCSelect>
                  )}
                </FormItem>
                <AddEmpForm
                  empNameList={empNameList}
                  empNameSelect={empNameSelect}
                  onSearch={this.empSearch}
                  empData={this.empData}
                  idVailFunc={this.idVailFunc}
                  loading={loading}
                />
                <Divider />
                <Row style={{ textAlign: 'center', justifyContent: 'center' }}>
                  <Button onClick={this.close}>关闭</Button>
                  <Button
                    style={{ marginLeft: 30 }}
                    type="primary"
                    onClick={() => this.next()}
                    disabled={btnDis}
                  >
                    下一步
                  </Button>
                </Row>
              </Card>
            )}
            {current === 1 && (
              <div>
                <div>
                  <AddEmpInfor
                    empSendInfoVo={empSendInfoVo}
                    empBaseInfoVo={empBaseInfoVo}
                    loading={loading}
                  />
                  <Card title={<span>业务信息</span>}>
                    <Form layout="inline">
                      <Row>
                        <Col span={8}>
                          <FormItem label="服务类型:">{serTypeName}</FormItem>
                        </Col>
                        <Col span={8}>
                          <FormItem label="是否有返款:">
                            {getFieldDecorator('refundFlag', {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择是否有返款',
                                },
                              ],
                              initialValue: '2',
                            })(
                              <RadioGroup onChange={this.refunds}>
                                <Radio value="2">无返款</Radio>
                                <Radio value="1">有返款</Radio>
                              </RadioGroup>
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                    </Form>
                    <Form>
                      {String(refundFlag) === '1' ? (
                        <Row
                          style={{
                            backgroundColor: '#fafafa',
                            height: 60,
                            marginTop: 5,
                          }}
                        >
                          <Col span={8}>
                            <FormItem
                              {...formItemLayouts}
                              label="收款方信息:"
                              style={{
                                marginTop: 15,
                                marginLeft: -20,
                              }}
                            >
                              {getFieldDecorator('payeeName', {
                                rules: [
                                  {
                                    required: false,
                                    message: '请输入不超过50个字符的收款方信息',
                                    max: 50,
                                  },
                                ],
                              })(<Input placeholder="请输入收款方信息" />)}
                            </FormItem>
                          </Col>
                          <Col span={8} className={styles.triangle}>
                            <FormItem
                              {...formItemLayouts}
                              label="收款方银行账号:"
                              style={{
                                marginTop: 15,
                              }}
                            >
                              {getFieldDecorator('payeeBankcardNo', {
                                rules: [
                                  {
                                    required: false,
                                    message: '请输入不超过30个字符的收款方银行账号',
                                    pattern: /^[0-9]{1,30}$/,
                                  },
                                ],
                              })(<Input placeholder="请输入收款方银行账号" />)}
                            </FormItem>
                          </Col>
                          <Col span={8}>
                            <FormItem
                              {...formItemLayouts}
                              label="开户行信息:"
                              style={{
                                marginTop: 15,
                              }}
                            >
                              {getFieldDecorator('payeeBankOfDepo', {
                                rules: [
                                  {
                                    required: false,
                                    message: '请输入不超过50个字符的开户行信息',
                                    max: 50,
                                  },
                                ],
                              })(<Input placeholder="请输入开户行信息" />)}
                            </FormItem>
                          </Col>
                        </Row>
                      ) : null}
                    </Form>

                    {String(coltFlag) === '1' && (
                      <div>
                        <Divider />
                        <div>
                          {matFileDictItem && matFileDictItem.length ? (
                            <div>
                              <Row>
                                <Col span={8}>
                                  <FormItem {...formItemLayouts} label="原件材料:">
                                    {getFieldDecorator('masterFiles', {
                                      rules: [
                                        {
                                          required: false,
                                          message: '请选择原件材料',
                                        },
                                      ],
                                    })(
                                      <HOCSelect
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择原件材料"
                                        onChange={this.aaa}
                                      >
                                        {matFileDictItem && matFileDictItem.length
                                          ? matFileDictItem.map(options => (
                                              <Option key={options.itemCode}>
                                                {options.itemName}
                                              </Option>
                                            ))
                                          : null}
                                      </HOCSelect>
                                    )}
                                  </FormItem>
                                </Col>
                              </Row>
                              <Row>
                                <Col span={8}>
                                  <FormItem {...formItemLayouts} label="复印件材料:">
                                    {getFieldDecorator('copyFiles', {
                                      rules: [
                                        {
                                          required: false,
                                          message: '请选择复印件材料',
                                        },
                                      ],
                                    })(
                                      <HOCSelect
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择复印件材料"
                                      >
                                        {matFileDictItem && matFileDictItem.length
                                          ? matFileDictItem.map(options => (
                                              <Option key={options.itemCode}>
                                                {options.itemName}
                                              </Option>
                                            ))
                                          : null}
                                      </HOCSelect>
                                    )}
                                  </FormItem>
                                </Col>
                              </Row>
                            </div>
                          ) : null}
                          <div>
                            {renderElem(elementArr)}
                            <div>
                              <Col span={14} offset={1}>
                                <FormItem {...formItemLayouts} label="材料是否完整:">
                                  {getFieldDecorator('matFlag', {
                                    rules: [
                                      {
                                        required: true,
                                        message: '请选择材料是否完整',
                                      },
                                    ],
                                  })(
                                    <RadioGroup>
                                      <Radio value="1">是</Radio>
                                      <Radio value="2">否</Radio>
                                    </RadioGroup>
                                  )}
                                </FormItem>
                              </Col>
                            </div>
                          </div>{' '}
                        </div>
                      </div>
                    )}
                    <Divider />
                    <Row style={{ textAlign: 'center', justifyContent: 'center' }}>
                      <Button onClick={this.close}>关闭</Button>
                      <Button style={{ marginLeft: 16 }} onClick={() => this.prev()}>
                        上一步
                      </Button>
                      <Button style={{ marginLeft: 16 }} type="primary" onClick={() => this.save()} loading={loading}>
                        保存
                      </Button>
                      <Button
                        style={{ marginLeft: 16 }}
                        type="primary"
                        onClick={() => this.saveUpdate()}
                        loading={loading}
                      >
                        保存并提交运行
                      </Button>
                    </Row>
                  </Card>
                </div>
              </div>
            )}
          </div>
          <Modal title="提示" visible={visNext} onOk={this.okNext} onCancel={this.cancelNext}>
            <p>{Object.keys(messageData).length ? messageData : null}</p>
          </Modal>
        </PageHeaderWrapper>
      </div>
    );
  }
}
const AccuAddform = Form.create()(AccuAdd);
export default AccuAddform;
